package qinyi365;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;

import org.apache.log4j.Logger;
public class GetCoord {
	/**
	 * @param args
	 */
	protected static final Logger logger = Logger.getLogger(GetCoord.class);
	
	public double[] MCBAND = { 12890594.86, 8362377.87, 5591021, 3481989.83,
			1678043.12, 0 };

	public double[][] MC2LL = {
			{ 1.410526172116255e-8, 0.00000898305509648872, -1.9939833816331,
					200.9824383106796, -187.2403703815547, 91.6087516669843,
					-23.38765649603339, 2.57121317296198, -0.03801003308653,
					17337981.2 },
			{ -7.435856389565537e-9, 0.000008983055097726239,
					-0.78625201886289, 96.32687599759846, -1.85204757529826,
					-59.36935905485877, 47.40033549296737, -16.50741931063887,
					2.28786674699375, 10260144.86 },
			{ -3.030883460898826e-8, 0.00000898305509983578, 0.30071316287616,
					59.74293618442277, 7.357984074871, -25.38371002664745,
					13.45380521110908, -3.29883767235584, 0.32710905363475,
					6856817.37 },
			{ -1.981981304930552e-8, 0.000008983055099779535, 0.03278182852591,
					40.31678527705744, 0.65659298677277, -4.44255534477492,
					0.85341911805263, 0.12923347998204, -0.04625736007561,
					4482777.06 },
			{ 3.09191371068437e-9, 0.000008983055096812155, 0.00006995724062,
					23.10934304144901, -0.00023663490511, -0.6321817810242,
					-0.00663494467273, 0.03430082397953, -0.00466043876332,
					2555164.4 },
			{ 2.890871144776878e-9, 0.000008983055095805407, -3.068298e-8,
					7.47137025468032, -0.00000353937994, -0.02145144861037,
					-0.00001234426596, 0.00010322952773, -0.00000323890364,
					826088.5 } };

	public String url1 ="http://api.map.baidu.com/?qt=gc&wd=";
	public String url2 ="&cn=";
	public String url3 = "&ie=utf-8&oue=1&res=api&callback=BMap._rd._cbk29363";


	public static void main(String[] args) {
		Point p = new Point(Double.parseDouble("12951342.870000"), Double
				.parseDouble("4835926.370000"));
		GetCoord c = new GetCoord();
		Point t = c.convertMC2LL(p);
		System.out.println(t.lng + "    " + t.lat);
		c.getC("中国北京北京市朝阳区,北辰东路8号   五洲大酒店", "北京市");
	}

	public Point getC(String address,String city)
	{
		String uri = this.url1 + address + this.url2 + city + this.url3;
		String x = null;String y = null;
		try {
		URL url; url = new URL(uri.replace(" ", ""));
        HttpURLConnection conNet = (HttpURLConnection) url.openConnection();
        conNet.setConnectTimeout(5000);
        conNet.setReadTimeout(5000);
        conNet.setRequestMethod("GET");
        conNet.setRequestProperty("accept", "*/*");
        conNet.setRequestProperty("connection", "Keep-Alive");
        conNet.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conNet.setDoInput(true);
        BufferedReader br = null;
        int maxcount = 0;
        
        while(br == null && maxcount++ < 5)
        {
            try{
             br = new BufferedReader(new InputStreamReader(
                    conNet.getInputStream(), "utf-8"));
            }catch(IOException e )
            {
            	logger.info(e.getMessage());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                    logger.info(e1.getMessage());
                }
            }
        }
        String s = "";
        String returnedString = "";
        while ((s = br.readLine()) != null) {
        	  returnedString += s;
        }
        br.close();
        //returnedString: BMap._rd._cbk29363 && BMap._rd._cbk29363(
        //{"content":{"cn":"\u5317\u4eac\u5e02","coord":{"x":"12950473.860000","y":"4835540.620000"},"prc":0,"sc":131,"wd":"\u4e2d\u56fd\u5317\u4eac\u5317\u4eac\u5e02\u6d77\u6dc0\u533a,\u77e5\u6625\u4e1c\u91cc11\u53f7\u697c1802"},"current_city":{"code":131,"geo":".=hWJPNB0A8wcA;","level":12,"name":"\u5317\u4eac\u5e02","sup_bus":1,"sup_business_area":1,"sup_lukuang":1,"sup_subway":1,"type":2,"up_province_name":"\u5317\u4eac\u5e02"},"hot_city":["\u4e0a\u6d77\u5e02|289","\u5e7f\u5dde\u5e02|257","\u6df1\u5733\u5e02|340","\u6210\u90fd\u5e02|75","\u5929\u6d25\u5e02|332","\u5357\u4eac\u5e02|315","\u676d\u5dde\u5e02|179","\u6b66\u6c49\u5e02|218","\u91cd\u5e86\u5e02|132","\u82cf\u5dde\u5e02|224"],"result":{"callback":"BMap._rd._cbk29363","cb_wd":"\u4e2d\u56fd\u5317\u4eac\u5317\u4eac\u5e02\u6d77\u6dc0\u533a,\u77e5\u6625\u4e1c\u91cc11\u53f7\u697c1802","cn":"\u5317\u4eac\u5e02","error":0,"ie":"utf-8","little_capacity":[],"oue":"1","qt":"gc","res":"api","type":35,"wd":"\u4e2d\u56fd\u5317\u4eac\u5317\u4eac\u5e02\u6d77\u6dc0\u533a,\u77e5\u6625\u4e1c\u91cc11\u53f7\u697c1802"}})
        //System.out.println(returnedString);
        if(returnedString.length() > 0)
        {
        	returnedString = returnedString.substring(returnedString.indexOf("\"coord"));
        	returnedString = returnedString.substring(0,returnedString.indexOf("}") + 1);
        	returnedString = returnedString.substring(returnedString.indexOf("\"x\":\"") + 5);
        	 x = returnedString.split("\",\"")[0];
        	 y = returnedString.split("\",\"")[1];
        	y = y.split("\":\"")[1].split("\"")[0];
        }
		} catch (Exception e2) {
			logger.info(e2.getMessage());
			e2.printStackTrace();
		} 
		if(x != null && y!= null)
		{
			Point p = new Point(Double.parseDouble(x), Double
					.parseDouble(y));
			Point t = convertMC2LL(p);
			return t;
		}
		else
			return null;
	}
	public Point convertMC2LL(Point cy) {
		Point cz = new Point(Math.abs(cy.lng), Math.abs(cy.lat));
		double[] cB = {};
		for (int cA = 0; cA < this.MCBAND.length; cA++) {
			if (cz.lat >= this.MCBAND[cA]) {
				cB = this.MC2LL[cA];
				break;
			}
		}
		Point T = this.convertor(cy, cB);
		DecimalFormat df = new DecimalFormat("0.000000");
		cy = new Point(Double.valueOf(df.format(T.lng)), Double.valueOf(df.format(T.lat)));
		return cy;
	}

	public Point convertor(Point cz, double[] cA) {
		double T = cA[0] + cA[1] * Math.abs(cz.lng);
		double cy = Math.abs(cz.lat) / cA[9];
		double cB = cA[2] + cA[3] * cy + cA[4] * cy * cy + cA[5] * cy * cy * cy
				+ cA[6] * cy * cy * cy * cy + cA[7] * cy * cy * cy * cy * cy
				+ cA[8] * cy * cy * cy * cy * cy * cy;
		T *= (cz.lng < 0 ? -1 : 1);
		cB *= (cz.lat < 0 ? -1 : 1);
		return new Point(T, cB);
	}
}

